package com.chatplus.application.web.advice;

import cn.hutool.core.io.IoUtil;
import com.chatplus.application.common.crypto.Crypto;
import com.chatplus.application.common.crypto.CryptoBody;
import com.chatplus.application.common.crypto.CryptoValue;
import com.chatplus.application.common.crypto.RequestMessageDecryptor;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@SuppressWarnings("NullableProblems")
@ControllerAdvice
public class DecryptRequestBodyAdvice extends RequestBodyAdviceAdapter {

    static final String ATTR_REQUEST_BODY_CIPHER_TEXT = "_ATTR_REQUEST_BODY_CIPHER_TEXT_";

    private final HttpServletRequest request;
    private final RequestMessageDecryptor requestMessageDecryptor;

    public DecryptRequestBodyAdvice(HttpServletRequest request, RequestMessageDecryptor requestMessageDecryptor) {
        this.requestMessageDecryptor = requestMessageDecryptor;
        this.request = request;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        if (CryptoBody.class.isAssignableFrom(parameter.getParameterType())) {
            return new HttpInputMessage() {
                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }

                @Override
                public InputStream getBody() throws IOException {
                    MediaType contentType = inputMessage.getHeaders().getContentType();
                    Charset charset = null;
                    if (contentType != null) {
                        charset = contentType.getCharset();
                    }
                    if (charset == null) {
                        charset = StandardCharsets.UTF_8;
                    }
                    String cipherText = IoUtil.read(inputMessage.getBody(), charset);
                    request.setAttribute(ATTR_REQUEST_BODY_CIPHER_TEXT, cipherText);
                    return new ByteArrayInputStream(requestMessageDecryptor.decrypt(cipherText).getBytes(charset));
                }
            };
        }

        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (!CryptoBody.class.isAssignableFrom(parameter.getParameterType())) {
            ReflectionUtils.doWithFields(body.getClass(), field -> {
                ReflectionUtils.makeAccessible(field);
                Object cryptoValue = ReflectionUtils.getField(field, body);

                if (cryptoValue instanceof CryptoValue && StringUtils.isNotBlank(((CryptoValue) cryptoValue).getCipherText())) {
                    ((CryptoValue) cryptoValue).setRawText(requestMessageDecryptor.decrypt(((CryptoValue) cryptoValue).getCipherText()));
                } else if (field.isAnnotationPresent(Crypto.class) && cryptoValue instanceof String) {
                    String rawText = requestMessageDecryptor.decrypt(((String) cryptoValue));
                    ReflectionUtils.setField(field, body, rawText);
                }
            }, field -> CryptoValue.class.isAssignableFrom(field.getType()) || field.isAnnotationPresent(Crypto.class));
        } else {
            ((CryptoBody) body).setCipherBody((String) request.getAttribute(ATTR_REQUEST_BODY_CIPHER_TEXT));
            request.removeAttribute(ATTR_REQUEST_BODY_CIPHER_TEXT);
        }

        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }
}
